/*
 * Copyright 2005-2013 finalist.cn. All rights reserved.
 * Support: http://www.finalist.cn
 * License: http://www.finalist.cn/license
 */
package com.finalist.dao.impl;

import java.util.List;

import javax.persistence.FlushModeType;
import javax.persistence.NoResultException;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

import com.finalist.dao.PaymentDao;
import com.finalist.entity.Payment;

/**
 * Dao - 收款单
 * 
 * @author Finalist IT Group
 * @version 3.0
 */
@Repository("paymentDaoImpl")
public class PaymentDaoImpl extends BaseDaoImpl<Payment, Long> implements PaymentDao
{
    private static final Log log = LogFactory.getLog(PaymentDaoImpl.class);

    public Payment findBySn(String sn)
    {
        if (sn == null)
        {
            return null;
        }
        String jpql = "select payment from Payment payment where lower(payment.sn) = lower(:sn)";
        try
        {
            return entityManager.createQuery(jpql, Payment.class).setFlushMode(FlushModeType.COMMIT).setParameter("sn", sn).getSingleResult();
        }
        catch (Exception e)
        {
        	e.printStackTrace();
        	log.error(e.toString());
            return null;
        }
    }

    @Override
    public Payment findByChargeLogId(Long chargeLogId)
    {
        if (chargeLogId == null)
        {
            return null;
        }

        String jpql = "select payment from Payment payment where lower(payment.chargeLog) = lower(:chargeLogId) order by payment.createDate desc";
        List<Payment> paymentList = entityManager.createQuery(jpql, Payment.class).setFlushMode(FlushModeType.COMMIT).setParameter("chargeLogId", chargeLogId).getResultList();

        if (CollectionUtils.isEmpty(paymentList))
        {
            return null;
        }
        return paymentList.get(0);
    }

	@Override
	public Payment findByorderId(Long orderId) {
		 if (orderId == null)
	        {
	            return null;
	        }

	        String jpql = "select payment from Payment payment where lower(payment.order) = lower(:orderId) order by payment.createDate desc";
	        List<Payment> paymentList = entityManager.createQuery(jpql, Payment.class).setFlushMode(FlushModeType.COMMIT).setParameter("orderId", orderId).getResultList();

	        if (CollectionUtils.isEmpty(paymentList))
	        {
	            return null;
	        }
	        return paymentList.get(0);
	}

}